# -*- coding: UTF-8 -*-
"""
七牛云资源下载模块
"""
import requests
from qiniu import Auth
from ConfigParser import ConfigParser
from qiniu.services.cdn.manager import create_timestamp_anti_leech_url
import time
import os


class Downloader:

    def __init__(self):
        configfile = '\\'.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))).split('\\')[:-1])+'\\conf\\global.conf'
        config = ConfigParser()
        config.read(configfile)
        self.access_key = config.get('qiniu', 'access_key')
        self.secret_key = config.get('qiniu', 'secret_key')
        self.private_bucket_domain = config.get('qiniu','private_bucket_domain')
        self.public_bucket_domain = config.get('qiniu', 'public_bucket_domain')

    def getprivateurl(self,key):
        q = Auth(self.access_key, self.secret_key)
        #构造base_url
        base_url = 'http://%s/%s' % (self.private_bucket_domain, key)
        #可以设置token过期时间
        private_url = q.private_download_url(base_url, expires=3600)
        #r = requests.get(private_url)
        #assert r.status_code == 200 ,'访问文件失败，可能文件不存在！'
        return private_url

    def getpublicurl(self,file_name='default.jpg'):
        """
        获取公有资源url
        """
        host = 'http://%s' % self.public_bucket_domain
        # 资源路径
        file_name = file_name
        url=host+'/%s' % file_name
        return url

if __name__ == '__main__':
    d = Downloader()
    url = d.getprivateurl('0000101.mp4')
    print url
    url=d.getpublicurl()
    print url
